using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoStartManager.Models;

namespace AutoStartManager.Services
{
    /// <summary>
    /// 进程监控服务
    /// </summary>
    public class ProcessMonitor
    {
        private readonly ConfigManager _configManager;
        private System.Windows.Forms.Timer _monitorTimer;
        private List<ManagedApp> _managedApps;
        private readonly string _logFilePath;

        public event EventHandler<AppStatusChangedEventArgs>? AppStatusChanged;

        public ProcessMonitor(ConfigManager configManager)
        {
            _configManager = configManager;
            _managedApps = new List<ManagedApp>();
            _logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "AutoStartManager_Debug.log");
            InitializeTimer();
        }

        private void InitializeTimer()
        {
            _monitorTimer = new System.Windows.Forms.Timer
            {
                Interval = 60000 // 1分钟 = 60000毫秒
            };
            _monitorTimer.Tick += OnMonitorTimerTick;
        }

        private void LogDebug(string message)
        {
            try
            {
                var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}";
                System.Diagnostics.Debug.WriteLine(logMessage);
                File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
            }
            catch
            {
                // 忽略日志写入错误
            }
        }

        /// <summary>
        /// 开始监控
        /// </summary>
        public void StartMonitoring()
        {
            LoadManagedApps();
            _monitorTimer.Start();
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        public void StopMonitoring()
        {
            _monitorTimer.Stop();
        }

        /// <summary>
        /// 手动检查所有管理的应用程序状态
        /// </summary>
        public async Task CheckAllAppsStatusAsync()
        {
            await CheckManagedAppsAsync(true); // 强制触发状态更新事件
        }

        /// <summary>
        /// 加载管理的应用程序
        /// </summary>
        public void LoadManagedApps()
        {
            var (apps, _) = _configManager.LoadConfig();
            var newApps = apps.Where(app => app.IsEnabled).ToList();
            
            // 保留现有应用的状态信息（除了ProcessId，因为不再依赖它）
            foreach (var newApp in newApps)
            {
                var existingApp = _managedApps.FirstOrDefault(a => 
                    string.Equals(a.Name, newApp.Name, StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(a.ExecutablePath, newApp.ExecutablePath, StringComparison.OrdinalIgnoreCase));
                
                if (existingApp != null)
                {
                    // 只保留IsRunning和LastChecked状态，ProcessId会在检测时重新获取
                    newApp.IsRunning = existingApp.IsRunning;
                    newApp.LastChecked = existingApp.LastChecked;
                }
            }
            
            _managedApps = newApps;
        }

        /// <summary>
        /// 添加管理的应用程序
        /// </summary>
        public void AddManagedApp(ManagedApp app)
        {
            _managedApps.Add(app);
        }

        /// <summary>
        /// 移除管理的应用程序
        /// </summary>
        public void RemoveManagedApp(ManagedApp app)
        {
            _managedApps.Remove(app);
        }

        /// <summary>
        /// 获取当前运行的进程列表
        /// </summary>
        public List<ProcessInfo> GetRunningProcesses()
        {
            var processes = new List<ProcessInfo>();
            
            try
            {
                var runningProcesses = Process.GetProcesses()
                    .Where(p => !string.IsNullOrEmpty(p.ProcessName) && p.Id != Process.GetCurrentProcess().Id)
                    .OrderBy(p => p.ProcessName);

                foreach (var process in runningProcesses)
                {
                    try
                    {
                        processes.Add(new ProcessInfo
                        {
                            Id = process.Id,
                            Name = process.ProcessName,
                            MainWindowTitle = process.MainWindowTitle,
                            StartTime = process.StartTime,
                            ExecutablePath = GetProcessExecutablePath(process)
                        });
                    }
                    catch
                    {
                        // 忽略无法访问的进程
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误但不抛出异常
                System.Diagnostics.Debug.WriteLine($"获取进程列表失败: {ex.Message}");
            }

            return processes;
        }

        private string GetProcessExecutablePath(Process process)
        {
            try
            {
                return process.MainModule?.FileName ?? string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        private async void OnMonitorTimerTick(object? sender, EventArgs e)
        {
            await CheckManagedAppsAsync(false); // 正常监控，只在状态变化时触发事件
        }

        /// <summary>
        /// 检查管理的应用程序状态
        /// </summary>
        private async Task CheckManagedAppsAsync(bool forceUpdate = false)
        {
            await Task.Run(() =>
            {
                foreach (var app in _managedApps)
                {
                    try
                    {
                        bool isRunning = IsAppRunning(app);
                        bool wasRunning = app.IsRunning;
                        
                        app.IsRunning = isRunning;
                        app.LastChecked = DateTime.Now;

                        // 如果状态发生变化或者强制更新，则触发事件
                        if (wasRunning != isRunning || forceUpdate)
                        {
                            AppStatusChanged?.Invoke(this, new AppStatusChangedEventArgs
                            {
                                App = app,
                                IsRunning = isRunning,
                                WasRunning = wasRunning
                            });
                        }

                        // 如果应用未运行且启用了监控，则启动应用
                        if (!isRunning && app.IsEnabled)
                        {
                            StartApp(app);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogDebug($"检查应用 {app.Name} 状态失败: {ex.Message}");
                    }
                }
            });
        }

        /// <summary>
        /// 检查应用程序是否正在运行
        /// </summary>
        private bool IsAppRunning(ManagedApp app)
        {
            try
            {
                LogDebug($"检查应用: {app.Name}, 路径: {app.ExecutablePath}");

                // 通过进程名和路径检查
                var processName = Path.GetFileNameWithoutExtension(app.ExecutablePath);
                LogDebug($"进程名: {processName}");
                
                if (string.IsNullOrEmpty(processName))
                {
                    LogDebug("进程名为空，返回false");
                    return false;
                }

                var processes = Process.GetProcessesByName(processName);
                LogDebug($"找到 {processes.Length} 个同名进程");
                
                foreach (var process in processes)
                {
                    try
                    {
                        var processPath = GetProcessExecutablePath(process);
                        LogDebug($"进程 {process.Id} 路径: {processPath}");
                        
                        if (!string.IsNullOrEmpty(processPath))
                        {
                            // 标准化路径进行比较
                            var normalizedProcessPath = Path.GetFullPath(processPath);
                            var normalizedAppPath = Path.GetFullPath(app.ExecutablePath);
                            
                            LogDebug($"标准化进程路径: {normalizedProcessPath}");
                            LogDebug($"标准化应用路径: {normalizedAppPath}");
                            
                            if (string.Equals(normalizedProcessPath, normalizedAppPath, StringComparison.OrdinalIgnoreCase))
                            {
                                // 找到匹配的进程，更新ProcessId（仅用于显示）
                                app.ProcessId = process.Id;
                                LogDebug($"找到匹配进程，更新ProcessId为: {process.Id}");
                                return true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogDebug($"检查进程 {process.Id} 失败: {ex.Message}");
                        // 忽略无法访问的进程
                        continue;
                    }
                }

                LogDebug($"未找到匹配的进程，返回false");
                // 未找到匹配进程时，重置ProcessId
                app.ProcessId = 0;
                return false;
            }
            catch (Exception ex)
            {
                LogDebug($"检查应用 {app.Name} 状态时发生异常: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 启动应用程序
        /// </summary>
        private void StartApp(ManagedApp app)
        {
            try
            {
                var startInfo = new ProcessStartInfo
                {
                    FileName = app.ExecutablePath,
                    Arguments = app.Arguments,
                    WorkingDirectory = string.IsNullOrEmpty(app.WorkingDirectory) ? Path.GetDirectoryName(app.ExecutablePath) : app.WorkingDirectory,
                    UseShellExecute = true
                };

                var process = Process.Start(startInfo);
                if (process != null)
                {
                    app.ProcessId = process.Id;
                    System.Diagnostics.Debug.WriteLine($"已启动应用: {app.Name}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"启动应用 {app.Name} 失败: {ex.Message}");
            }
        }
    }

    /// <summary>
    /// 进程信息
    /// </summary>
    public class ProcessInfo
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string MainWindowTitle { get; set; } = string.Empty;
        public DateTime StartTime { get; set; }
        public string ExecutablePath { get; set; } = string.Empty;
    }

    /// <summary>
    /// 应用状态改变事件参数
    /// </summary>
    public class AppStatusChangedEventArgs : EventArgs
    {
        public ManagedApp App { get; set; } = new();
        public bool IsRunning { get; set; }
        public bool WasRunning { get; set; }
    }
}